package com.fh.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class collectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        //这里演示Collection接口遍历元素方式1-使用Iterator（迭代器）
        //1）Iterator对象称为迭代器，主要用于遍历Collection集合中的元素
        //2）所有实现了Collection接口的集合类都有一个iterator()方法，用以返回一个实现了Iterator接口的对象，即可以返回一个迭代器
        //3）Iterator仅用于遍历集合，Iterator本身并不存放对象
        Collection col = new ArrayList();
        col.add(new Book("三国演义","罗贯中",30.5));
        col.add(new Book("小李飞刀","古龙",30.1));
        col.add(new Book("红楼梦","曹雪芹",30.6));
        System.out.println(col);//这种格式不是很好看，我想将其进行遍历，抽取出来
        //1. 首先创建一个迭代器
        Iterator iterator = col.iterator();
        //2. 使用while循环遍历
        //快捷键使用：快速生成 while => itit
        //查看所有快捷键的快捷键 ctrl+j
        while (iterator.hasNext()) {//判断后面是否有数据
            //返回下一个元素，类型是Object
            Object obj =  iterator.next();
            System.out.println("obj"+obj);
        }
        //3. 当退出while循环后，这时iterator迭代器，会指向最后的元素
//        iterator.next();//抛出异常
        //4. 如果希再次遍历，需要我们重置迭代器
        iterator = col.iterator();
        System.out.println("=========第二次遍历===========");
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            Book book = (Book) obj;
            System.out.println(book);
        }


    }
}
class Book{
    private String name;
    private String author;
    private double price;
    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

